package it.unipd.dei.project.iandroid;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

/**
 * 
 * Activity contenente la lista degli eventi
 * 
 */
public class EventManager extends Activity {

	DatabaseOpenHelper db;
	SQLiteDatabase base;
	Cursor cur;
	EditText txt;
	String[] squadre2 = new String[] {};
	ArrayList<String> list = new ArrayList<String>(Arrays.asList(squadre2));
	ArrayAdapter<String> adapter;

	private ArrayList<Event> leagues = new ArrayList<Event>(10);
	private EventAdapter eAdapter = null;
	int selected;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event_manager);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setContentView(R.layout.activity_event_manager);

		// pulisco l'ArrayList ogni volta che viene richiamato l'onResume()
		leagues.clear();
		db = new DatabaseOpenHelper(this);
		base = db.getWritableDatabase();

		// riempio l'ArrayList con i dati degli eventi
		cur = base.query("Evento", null, null, null, null, null, "PeriodoIniziale DESC");

		for (int i = 0; i < cur.getCount(); i++) {
			cur.moveToNext();

			leagues.add(new Event(cur.getString(0), cur.getString(1) + " / " + cur.getString(2), cur.getString(3),
					BitmapFactory.decodeResource(this.getResources(), R.drawable.coppa)));
		}
		cur.close();
		base.close();
		db.close();

		ListView event = (ListView) findViewById(R.id.list);
		eAdapter = new EventAdapter(this, R.layout.event_adapter_layout, leagues);
		event.setAdapter(eAdapter);

		event.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> listView, View itemView, int position, long itemId) {

				Intent listMatch = new Intent(EventManager.this, MatchManager.class);
				String pkg = getPackageName();
				listMatch.putExtra(pkg + "pos", position);
				startActivity(listMatch);

				System.err.println("Hai selezionato " + listView.getItemAtPosition(position));
				System.err.println("con id = " + itemId + " e position = " + position);
			}
		});

		event.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> listView, View itemView, int position, long itemId) {
				selected = (int) position;
				System.err.println("Hai selezionato " + selected);
				return false;
			}
		});

		// serve per attivare il long click
		registerForContextMenu(event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.event_manager_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.opzEvento:
			Intent iEdit = new Intent(getBaseContext(), OptionsEvent.class);
			iEdit.putExtra("eTipo", "nuovo");
			startActivity(iEdit);
			return true;
		}
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_squadre, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final String eNome = leagues.get(selected).getName();
		String ePeriodo = leagues.get(selected).getPeriod();
		Scanner sPeriodo = new Scanner(ePeriodo);
		final String eInizio = sPeriodo.next();
		String tmp = sPeriodo.next();
		tmp = sPeriodo.next();
		final String eFine = tmp;
		String eTeam = leagues.get(selected).getTeam();
		switch (item.getItemId()) {
		case R.id.edit:
			Intent iEdit = new Intent(getBaseContext(), OptionsEvent.class);
			iEdit.putExtra("eTipo", "modifica");
			iEdit.putExtra("eNome", eNome);
			iEdit.putExtra("eInizio", eInizio);
			iEdit.putExtra("eFine", eFine);
			iEdit.putExtra("eTeam", eTeam);
			startActivity(iEdit);
			return true;
		case R.id.delete:
			AlertDialog.Builder miaAlert = new AlertDialog.Builder(this);
			miaAlert.setTitle("Attenzione");
			miaAlert.setMessage("Verranno cancellate anche tutte le partite associate a quest'evento");
			miaAlert.setIcon(R.drawable.warning);
			miaAlert.setPositiveButton("Continua", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					db = new DatabaseOpenHelper(EventManager.this);
					base = db.getWritableDatabase();

					int d = base.delete("Evento", "Nome = '" + eNome + "' and PeriodoIniziale = '" + eInizio
							+ "' and PeriodoFinale = '" + eFine + "'", null);
					System.err.println("nome=" + eNome);
					System.err.println("i=" + eInizio);
					System.err.println("f=" + eFine);
					System.err.println("delete=" + d);
					base.close();
					db.close();
					onResume();
				}
			});
			miaAlert.setNegativeButton("Annulla", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			miaAlert.show();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onPause() {

		super.onPause();
		cur.close();
		base.close();
		db.close();

	}

}